package com.zkingsoft.actions.admin.pc;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zkingsoft.services.pc.PcFoodMaterialService;
import com.zkingsoft.services.pc.PcMenuDetailService;
import com.zkingsoft.services.pc.PcMenuManageService;
import com.zkingsoft.services.pc.PcMenuRecordService;
import com.zkingsoft.services.pc.PcMicroElementService;
import com.zkingsoft.model.pc.HelpMenuDetail;
import com.zkingsoft.model.pc.PcFoodMaterial;
import com.zkingsoft.model.pc.PcMenuDetail;
import com.zkingsoft.model.pc.PcMenuManage;
import com.zkingsoft.model.pc.PcMenuRecord;
import com.zkingsoft.model.pc.PcMicroElement;
import com.zkingsoft.authority.MatrixAdapter;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.util.ExcelUtil.ViewExcel;
import com.zkingsoft.util.WebUtil;
import com.zkingsoft.constraint.BaseController;
import com.zkingsoft.pojo.AjaxResult;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.anotations.RemoveRequestToken;

/**
 * This field was generated by Zking.software.Codegen.
 * @date 2017-03-24 11:05
 */
@Controller
@RequestMapping(value = "admin/pcMenuDetail")
public class PcMenuDetailController extends BaseController{

	Logger log = Logger.getLogger(this.getClass());
	
	@Resource
	private PcMenuDetailService pcMenuDetailService;
	@Resource
	private PcMenuManageService pcMenuManageService;
	@Resource
	private MatrixAdapter matrixAdapter;
	@Resource
	private PcFoodMaterialService PcFoodMaterialService;
	@Resource
	private PcMenuRecordService pcMenuRecordService;
	@Resource
	private PcMicroElementService pcMicroElementService;
	//记录编辑前的值Before_Edit_Value
	public static final String BEV="PcMenuDetail_BEV";
	
	public static final String fnCode = "PcMenuDetail";
	public static final String search = fnCode + ":search";
	public static final String edit = fnCode + ":edit";
	public static final String del = fnCode + ":del";
	public static final String add = fnCode + ":add";
	private static List<HelpMenuDetail> detailList=null;
	/**
	 * 修改原材料页面
	 */   
	@RemoveRequestToken	
   	@RequestMapping(value = "/addOrModify-material")
	public @ResponseBody AjaxResult addOrModify(PcFoodMaterial pcFoodMaterial) {
		List<PcFoodMaterial> materialList = pcFoodMaterial.getMaterialList();
		String materialIds="";
		int i=0;
		Long id=null;
		if(materialList != null){
			for(PcFoodMaterial m:materialList){
				if(m != null && m.getFodId()!= null ){
				i++;
				if(i>1){
					materialIds += ","+m.getFodId()+":"+m.getWeight();
				}else{
					materialIds = m.getFodId()+":"+m.getWeight();
				}
				id=m.getDetailMenId();
				}
			}
			PcMenuDetail pcMenuDetail=pcMenuDetailService.findById(id);
			pcMenuDetail.setMaterialIds(materialIds);
			int n = pcMenuDetailService.modifyByModel(pcMenuDetail);
			if (n > 0) {
				return new AjaxResult(AjaxResult.STATUS_OK, null, "修改成功");
			} 
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "修改失败");
	}
	/**
	 * 修改菜谱页面
	 */  
	@RemoveRequestToken	
   	@RequestMapping(value = "/addOrModify-food")
	public @ResponseBody AjaxResult addOrModify(PcMenuManage pcMenuManage) {
			int n = pcMenuDetailService.updateMaterial(pcMenuManage);
			if (n > 0) {
				return new AjaxResult(AjaxResult.STATUS_OK, null, "修改成功");
			} 
		
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "修改失败");
	}
	
   	/**
	 * 进入菜谱修改界面
	 */   
	@SaveRequestToken
   	@RequestMapping(value = "/editForm-food")
	public String editFormF(Long id) {		
		if (id != null) {
			PcMenuDetail pcMenuDetail=pcMenuDetailService.findById(id);
			String foodIds=pcMenuDetail.getFoodIds();
			PcMenuManage pcMenuManage;
			WebUtil.getRequest().setAttribute("menId", id);
			if(foodIds!= null){
				List<PcMenuManage> menuList = new ArrayList<PcMenuManage>();
				String[] fids=foodIds.split(",");
				for(int i=0;i<fids.length;i++){
					pcMenuManage = pcMenuManageService.findById(Long.parseLong(fids[i]));
					if(pcMenuManage!=null){
						pcMenuManage.setDetailMenId(id);
						menuList.add(pcMenuManage);
					}
					
				}
				WebUtil.getRequest().setAttribute("menuList", menuList);
			}
		}
		return "admin/pc/PcMenuDetail-form-food";
	}
	
	/**
	 * 进入原材料修改界面
	 */   
	@SaveRequestToken
   	@RequestMapping(value = "/editForm-material")
	public String editFormM(Long id) {		
		if (id != null) {
			PcMenuDetail pcMenuDetail=pcMenuDetailService.findById(id);
			String materialIds=pcMenuDetail.getMaterialIds();
				List<PcFoodMaterial> materialList = new ArrayList<PcFoodMaterial>();
				String[] mids=materialIds.split(",");
				for(int i=0;i<mids.length;i++){
					if(mids[i] != null){
						String[]  arr=mids[i].split(":");
						if(arr != null && arr.length>1){
							PcFoodMaterial fodm=PcFoodMaterialService.findById(Long.parseLong(arr[0]));
							if(fodm!=null){
								fodm.setWeight(arr[1]);
								fodm.setDetailMenId(id);
								materialList.add(fodm);
							}
						}
					}
				}
				WebUtil.getRequest().setAttribute("menId", id);
				WebUtil.getRequest().setAttribute("materialList", materialList);
			}
		return "admin/pc/PcMenuDetail-form-material";
	}
   	/**
	 * 删除
	 */  
 	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		matrixAdapter.isBtnPermitted(del);
		return remove(pcMenuDetailService, keys);
	}
 	/**  
 	 *  @Description 菜谱明细表 对象
 		@author :heqiuyun
 		@date2017年3月25日
 	 */
 	@RequestMapping(value = "/showDetail")
	public @ResponseBody AjaxResult showDetail(Long id) {
 		AjaxResult result=new AjaxResult();
 		result.setStatus(AjaxResult.STATUS_OK);
 		PcMenuRecord pcMenuRecord = pcMenuRecordService.findById(id);
 		detailList=pcMenuDetailService.findFoods(pcMenuRecord,true);
 		result.setRows(pcMenuDetailService.findFoods(pcMenuRecord,true));
 		return result;
	}
 	/**  
 	 *  @Description 显示一周营养素供给量表
 		@author :heming
 		@date2017年3月25日
 	 */
 	@RequestMapping(value = "/showElement")
	public @ResponseBody AjaxResult showElement(Long id) {
 		AjaxResult result=new AjaxResult();
 		result.setStatus(AjaxResult.STATUS_OK);
 		PcMenuRecord pcMenuRecord = pcMenuRecordService.findById(id);
 		result.setRows(pcMenuDetailService.findElements(pcMenuRecord,detailList));
 		
 		return result;
	}
 	/**
 	 * 
 	 *  @Description 显示菜谱明细表
 		@author :heqiuyun
 		@date2017年3月26日
 	 */
 	@RequestMapping(value = "/showList")
	public String show(Long id) {
		if (id != null) {
			PcMenuRecord pcMenuRecord = pcMenuRecordService.findById(id);
			WebUtil.getRequest().setAttribute("beginTime", dateFormat(pcMenuRecord.getMenBeginTime(),1));
			WebUtil.getRequest().setAttribute("endTime", dateFormat(pcMenuRecord.getMenBeginTime(),5));
			WebUtil.getRequest().setAttribute("pcMenuRecord", pcMenuRecord);
			List<PcMicroElement> eleList=pcMicroElementService.findByModel(null);
			WebUtil.getRequest().setAttribute("eleList", eleList);
			WebUtil.setSessionAttribute(BEV, pcMenuRecord);
		}
		return  "admin/pc/PcMenuDetail-list";
	}
 	//格式化日期
 	public String dateFormat(Date date,int i){
	     Calendar calendar = new  GregorianCalendar(); 
	     calendar.setTime(date); 
	     calendar.add(calendar.DATE,i);//把日期往后增加i天.整数往后推,负数往前移动 
	     date=calendar.getTime();   //这个时间就是日期往后推一天的结果 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		String time = sdf.format(date);
		return time;
 	}
 	/**  
 	 *  @Description 获取当前时间的年月日
 		@author :heming
 		@date2017年4月1日
 	 */
 	public String getNowTime(){
 		Calendar ca = new GregorianCalendar();
 		String time=ca.get(Calendar.YEAR)+""
				+(ca.get(Calendar.MONTH)+1)+""
				+ca.get(Calendar.DAY_OF_MONTH);
		return time;
 		
 	}
	/**  
 	 *  @Description 导出c菜谱Excel
 		@author :heming
 		@date2017年4月1日
 	 */
 	@RequestMapping(value = "/exportMenu")
 	public @ResponseBody ModelAndView exportMenu(ModelMap model, HttpServletRequest request, HttpServletResponse response
 			,Long id) {
 		String time=getNowTime();
 		PcMenuRecord pcMenuRecord = pcMenuRecordService.findById(id);
 		String strTitle="日期： "+dateFormat(pcMenuRecord.getMenBeginTime(),1)+"  至    "
 				+dateFormat(pcMenuRecord.getMenBeginTime(),5)+
 				"        平均就餐人数："+pcMenuRecord.getMenManMun()
 				+" 人        单位：KG";
 		String[] title={"一周带量菜谱","菜谱营养素供给量"};
 		 String[][] headers={{"餐期","星期一","","星期二","","星期三","","星期四","","星期五",""},
 				 {"日期/标准","能量(kcal)","蛋白质(克)","脂肪(占能量的比率%)","碳水化合物(克)","胡萝卜素(微克)"
 				 		,"视黄醇当量(微克)","硫胺素(毫克)","核黄素(毫克)","尼克酸(毫克)","抗坏血栓(毫克)",
 				 		"钙(毫克)","铁(毫克)","磷(毫克)"}};
 		HSSFWorkbook workbook = pcMenuDetailService.generateExcelTwo(title, strTitle, headers,
 				pcMenuDetailService.exportTwoExcel(pcMenuRecord), "菜谱");
 		try {
			ViewExcel.buildExcel(null, workbook, request, response,"菜谱表"+time+".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
 			return new ModelAndView(new ViewExcel(), model);
 	}
 	/**  
 	 *  @Description 导出采购单Excel
 		@author :heming
 		@date2017年4月1日
 	 */
 	@RequestMapping(value = "/exportBuy")
 	public @ResponseBody ModelAndView exportBuy(ModelMap model, HttpServletRequest request, HttpServletResponse response
 			,Long id) {
 		String time=getNowTime();
 		PcMenuRecord pcMenuRecord = pcMenuRecordService.findById(id);
 		String strTitle="日期： "+dateFormat(pcMenuRecord.getMenBeginTime(),1)+"  至    "
 				+dateFormat(pcMenuRecord.getMenBeginTime(),5);
 		HSSFWorkbook workbook = pcMenuDetailService.generateExcel("采购单",strTitle,
				new String[] {"日期","采购材料"}, pcMenuDetailService.exportBuyExcel(pcMenuRecord),"采购");
 		try {
			ViewExcel.buildExcel(null, workbook, request, response,"采购单"+time+".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
 			return new ModelAndView(new ViewExcel(), model);
 	}

}
